<?php

namespace App\Library\Service;

use App\Library\Logic\ShopProductLogic;
use App\Library\Logic\ShopUserCollectLogic;
use App\Library\Requests\Base\BasePageRequest;
use App\Library\Requests\Base\IdRequest;
use App\Library\Requests\Base\SerialNumberRequest;
use Illuminate\Http\JsonResponse;

class CollectService extends BaseService
{
    /**
     * @param ShopUserCollectLogic $logic
     */
    public function __construct(ShopUserCollectLogic $logic)
    {
        $this->logic = $logic;
    }

    /**
     * 分页
     * @param BasePageRequest $request
     * @return JsonResponse
     */
    public function paging(BasePageRequest $request): JsonResponse
    {
        return success($this->logic->paging($request));
    }

    /**
     * 添加
     * @param SerialNumberRequest $request
     * @return JsonResponse
     */
    public function add(SerialNumberRequest $request): JsonResponse
    {
        $shopProduct = ShopProductLogic::findBySerialNumber($request, ['productId', 'productIsDelete', 'productStatus']);
        if (is_null($shopProduct)) return fail(433);
        $where = ['ucType' => 1, 'userId' => USERID, 'ucSourceId' => $shopProduct->product_id];
        if ($this->logic->existsByWhere($where)) return success();
        $this->logic->insertForModel($where);
        return success();
    }

    /**
     * delete
     * @param SerialNumberRequest $request
     * @return JsonResponse
     */
    public function delete(SerialNumberRequest $request): JsonResponse
    {
        $productId = ShopProductLogic::valueByWhere('serialNumber', $request->serialNumber, 'productId');
        if (is_null($productId)) return fail(433);
        $where = ['ucType' => 1, 'userId' => USERID, 'ucSourceId' => $productId];
        if ($this->logic->deleteByWhere($where)) return success();
        return success();
    }

    /**
     * detail
     * @param IdRequest $request
     * @return JsonResponse
     */
    public function detail(IdRequest $request): JsonResponse
    {
        $item = $this->logic->detail($request->id);
        if (is_null($item) || $item->user_id !== USERID) return fail(433);
        return success($item);
    }
}
